package com.lixin.springcloud.controller;

import com.alibaba.csp.sentinel.annotation.SentinelResource;
import com.alibaba.csp.sentinel.slots.block.BlockException;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.client.RestTemplate;

import java.util.concurrent.TimeUnit;

@RestController
@Slf4j
public class OrderController {

    @Value("${service-url.nacos-payment-service}")
    private String paymentServiceUrl;

    @Autowired
    private RestTemplate restTemplate;

    @GetMapping("/consumer/payment/nacos/{id}")
    public String index(@PathVariable("id") Integer id) {
        return restTemplate.getForObject(paymentServiceUrl + "/payment/nacos/" + id, String.class);
    }

    @GetMapping("/consumer/sentinelA")
    public String testSentinelA() {
        return "test sentinel A";
    }

    @GetMapping("/consumer/sentinelB")
    public String testSentinelB() {
        return "test sentinel B";
    }

    @GetMapping("/consumer/sentinelD")
    public String testSentinelD() {
        log.info("test sentinel D");
        int age = 5 / 0;
        return "test sentinel D";
    }


    @GetMapping("/consumer/sentinelE")
    public String testSentinelE() {
        try {
            TimeUnit.MILLISECONDS.sleep(200);
        } catch (InterruptedException e) {
            e.printStackTrace();
        }
        log.info("test sentinel E");
        return "test sentinel E";
    }

    @GetMapping("/testHotKey")
    @SentinelResource(value = "testHotKey", blockHandler = "testHotKeyFallback")
    public String testHotKey(
            @RequestParam(value = "p1", required = false) String p1,
            @RequestParam(value = "p2", required = false) String p2
    ) {
        return "测试热点规则 p1=" + p1 + " p2=" + p2;
    }

    public String testHotKeyFallback(String p1, String p2, BlockException exception) {
        return "测试时发生的异常，所以你就看见我了 p1=" + p1 + " p2=" + p2;
    }

}
